package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAcceptNotice;
import com.fingard.dsp.bank.reqrespobj.contract.ContractState;
import com.fingard.generalobj.NoticeReq;
import com.fingard.generalobj.NoticeResp;
import com.fingard.net.WebRequest;
import com.fingard.net.listener.SocketReceiver;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.util.Map;

public class CMB01AcceptNotice extends CMB01Base implements IAcceptNotice {

    @Override
    public NoticeResp dealNotice(NoticeReq pNtReq) throws Exception {

        if (getBankConfig().getValueAsBool("isAccept630")) {
            return d_dealNotice630(pNtReq);
        }
        WriteBankLogLn("回调通知开始保存本地==================");
        NoticeResp resp = new NoticeResp();
        String p_reqs = pNtReq.getReqString();
        WriteBankLogLn("接收到请求：" + pNtReq.getFullString());

        PrintStream ps = null;
        String tmpFileName = FGBiz.DSPHOME_Parent + File.separator + "signnotify";
        try {
            if (p_reqs.length() == 0) {
                String tmpStrRet = "空报文";
                WriteBankLogLn("响应：" + tmpStrRet);
                resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
                return resp;
            }


            File dir1 = new File(tmpFileName);
            if (!dir1.exists()) {
                dir1.mkdir();
            }
            Date a = new Date();
            File tmpFile1 = new File(tmpFileName + File.separator + Format.DateTime14Format.format(a) + ".txt");
            if (tmpFile1.exists()) {
                tmpFile1.delete();
            }
            tmpFile1.createNewFile();
            ps = new PrintStream(new FileOutputStream(tmpFile1));
            ps.println(p_reqs);
            ps.close();

            String p_req = "";
            if (p_reqs.contains("\n\n")) {
                //通过空白行截取字符串
                int index1 = p_reqs.indexOf("\n\n");
                p_req = p_reqs.substring(index1 + 2);
            } else {
                p_req = p_reqs;
            }

            WriteBankLogLn("签约通知报文：" + p_req);

            //写入文件的字符串
            StringBuilder reader_str = new StringBuilder();
            Map params = convertToMap(p_req);

            if (params != null) {
                boolean verify = true;

                if (verify) {
                    String status = params.get("xStsCod").toString();
                    String unifiedCode = "";
                    if (StringHelper.hasAnyChar(status)) {
                        if ("A".equalsIgnoreCase(status)) {
                            status = ContractState.SUCCESS;
                            unifiedCode = "SC000";
                        } else {
                            status = ContractState.FAIL;
                        }
                    } else {
                        status = ContractState.FAIL;
                    }
                    //签约、解约成功
                    reader_str.append("<ATSYH><TransResp><BankCode>CMB01</BankCode>");
                    reader_str.append("<TransType>QryContract</TransType>");
                    reader_str.append("<TransSeqID></TransSeqID>");
                    reader_str.append("<TransParam><DetailRecord><AuthCode>" + params.get("xCnvNbr").toString() + "</AuthCode>");
                    String pay_act = params.get("xCltEac").toString();
                    reader_str.append("<PayAct>" + pay_act + "</PayAct>");
                    reader_str.append("<SingleLimit>" + params.get("xPerAmt").toString() + "</SingleLimit>");
                    reader_str.append("<SignState>" + status + "</SignState>");
                    reader_str.append("<UnifiedCode>" + unifiedCode + "</UnifiedCode>");
                    reader_str.append("<DealLine>" + params.get("xExpDat").toString() + "</DealLine>");
                    reader_str.append("</DetailRecord></TransParam></TransResp></ATSYH>");

                    File dir = new File(tmpFileName);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    File tmpFile = new File(tmpFileName + File.separator + pay_act + ".txt");
                    if (tmpFile.exists()) {
                        tmpFile.delete();
                    }
                    tmpFile.createNewFile();
                    ps = new PrintStream(new FileOutputStream(tmpFile));
                    ps.println(reader_str);
                    ps.close();
                }
            } else {
                String tmpStrRet = "报文格式错误";
                WriteBankLogLn("响应：" + tmpStrRet);
                resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
                return resp;
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        } finally {
            if (ps != null) {
                ps.close();
            }
        }
        String tmpStrRet = "";
        WriteBankLogLn("响应：" + tmpStrRet);
        resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
        return resp;
    }

    @Override
    public void getContentLength(SocketReceiver p_receiver) throws Exception {

    }

    public NoticeResp d_dealNotice630(NoticeReq pNtReq) throws Exception {
        WriteBankLogLn("回调通知开始上送630=======================");

        NoticeResp resp = new NoticeResp();
        String p_reqs = pNtReq.getReqString();
        WriteBankLogLn("接收到请求：" + pNtReq.getFullString());
        try {
            if (p_reqs.length() == 0) {
                String tmpStrRet = "空报文";
                WriteBankLogLn("响应：" + tmpStrRet);
                resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
                return resp;
            }
            String p_req = "";
            if (p_reqs.contains("\n\n")) {
                //通过空白行截取字符串
                int index1 = p_reqs.indexOf("\n\n");
                p_req = p_reqs.substring(index1 + 2);
            } else {
                p_req = p_reqs;
            }
            WriteBankLogLn("签约通知报文：" + p_req);

            //写入文件的字符串
            StringBuilder reader_str = new StringBuilder();
            Map params = convertToMap(p_req);
            if (params != null) {
                String status = params.get("xStsCod").toString();
                String unifiedCode = "";
                if (StringHelper.hasAnyChar(status)) {
                    if ("A".equalsIgnoreCase(status)) {
                        status = ContractState.SUCCESS;
                        unifiedCode = "SC000";
                    } else {
                        status = ContractState.FAIL;
                    }
                } else {
                    status = ContractState.FAIL;
                }
                //上送630
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.writeStartDocument();
                xmlWriter.writeStartElement("ATSYH");
                xmlWriter.writeStartElement("TransResp");
                xmlWriter.writeElementString("BankCode", "CMB01");
                xmlWriter.writeElementString("TransType", "ContractNotify");
                xmlWriter.writeElementString("TransSeqID", "");
                xmlWriter.writeStartElement("TransParam");
                xmlWriter.writeStartElement("DetailRecord");
                xmlWriter.writeElementString("RespCode", "0");
                xmlWriter.writeElementString("RespInfo", "成功");
                xmlWriter.writeElementString("ReqSeqID", "");
                xmlWriter.writeElementString("PayAct", params.get("xCltEac").toString());

                xmlWriter.writeElementString("SignDate", params.get("xEftDat").toString());
                xmlWriter.writeElementString("SourceNoteCode", "");
                xmlWriter.writeElementString("PolicyNo", "");
                xmlWriter.writeElementString("OppActName", "");
                xmlWriter.writeElementString("CertType", "");
                xmlWriter.writeElementString("CertNumber", "");
                xmlWriter.writeElementString("CellPhone", "");
                xmlWriter.writeElementString("CurType", "");
                xmlWriter.writeElementString("NoteMoney", "");
                xmlWriter.writeElementString("BusType", params.get("xTrsUse").toString());
                xmlWriter.writeElementString("SignState", status);
                xmlWriter.writeElementString("UnifiedCode", unifiedCode);
                xmlWriter.writeElementString("AuthCode", params.get("xCnvNbr").toString());
                xmlWriter.writeEndDocument();
                String url = bankFront.getUrl("notifyURL");
                WriteBankLogLn("通知630的地址：" + url);
                String p_reqStr = xmlWriter.toXmlString();
                WriteBankLogLn("通知630的报文：" + p_reqStr);
                byte[] tmpToWriteBytes = p_reqStr.getBytes(getCharset());
                WebRequest tmpWebRequest = new WebRequest(url);
                tmpWebRequest.setConnectTimeout(600000);
                tmpWebRequest.setRequestProperty("Content-Type", "application/xml");
                tmpWebRequest.setRequestProperty("Connection", "keep-alive");
                tmpWebRequest.upload(tmpToWriteBytes, getCharset());
            } else {
                String tmpStrRet = "报文格式错误";
                WriteBankLogLn("响应：" + tmpStrRet);
                resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
                return resp;
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
        return resp;
    }

}
